package com.parleys.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import roboguice.inject.InjectExtra;
import roboguice.inject.InjectView;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.google.inject.Inject;
import com.parleys.R;
import com.parleys.adapter.ChapterListAdapter;
import com.parleys.androidservice.ParleysMediaPlayer;
import com.parleys.domain.Channel;
import com.parleys.domain.Presentation;
import com.parleys.domain.PresentationAsset;
import com.parleys.domain.Space;
import com.parleys.helper.ApplicationConstants;
import com.parleys.helper.DownloadTask;
import com.parleys.helper.TimeUtil;
import com.parleys.service.intf.DBAdapter;
import com.parleys.service.intf.ParleysService;

/**
 * Displays the chapters linked to a presentation. Clicking on a chapter plays the audio track at the selected chapter
 * (or moves the audio track to the new chapter when already playing).
 * 
 * @author David Van Droogenbroeck
 * 
 */
public class ChapterListActivity extends AbstractParleysActivity {

	private final static String TAG = ChapterListActivity.class.getName();

	private List<PresentationAsset> assets = new ArrayList<PresentationAsset>();

	private Boolean guiIsUpdating = false;

	@InjectExtra(ApplicationConstants.ONLINE_ARG)
	private Boolean online;

	@InjectExtra(ApplicationConstants.SPACE_ARG)
	private Space space;

	@InjectExtra(ApplicationConstants.CHANNEL_ARG)
	private Channel channel;

	@InjectExtra(ApplicationConstants.PRESENTATION_ARG)
	private Presentation presentation;

	@InjectView(R.id.list)
	private ListView listView;

	@Inject
	private DBAdapter dbAdapter;

	@Inject
	private ParleysService parleysService;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.parleys_list);

		List<PresentationAsset> tempAssets = parleysService.getPresentationAssets(presentation.getId(), online);

		setTitle(getString(R.string.chapters));

		for (PresentationAsset asset : tempAssets) {
			if (ApplicationConstants.IMAGE.equals(asset.getType())) {
				assets.add(asset);
			}
		}

		ChapterListAdapter chapterListAdapter = new ChapterListAdapter(this, assets);
		listView.setAdapter(chapterListAdapter);
		listView.setClickable(true);
		listView.setOnItemClickListener(new ChannelOnClickHandler());

	}

	@Override
	protected void onStart() {
		super.onStart();
		Handler handler = new Handler();
		if (ParleysMediaPlayer.isPlaying()) {
			guiIsUpdating = true;
		}
		handler.post(updateTimer);
	}

	@Override
	protected void onStop() {
		super.onStop();
		guiIsUpdating = false;
	}

	public class ChannelOnClickHandler implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> listview, View layout, int arg2, long arg3) {

			final Handler handler = new Handler();

			if (!guiIsUpdating) {
				handler.post(updateTimer);
				guiIsUpdating = true;
			}

			PresentationAsset asset = (PresentationAsset) ((ChapterListAdapter) listview.getAdapter()).getItem(arg2);
			int msecs = (int) (asset.getCuepoint() * 1000);

			// initialize mediaplayer if its not playing
			if (!ParleysMediaPlayer.isPlaying()) {
				if (online) {
					ParleysMediaPlayer.setDataSource(channel.getMediaBaseURL() + presentation.getId()
							+ presentation.getMp3());
				} else {
					File file = new File(ApplicationConstants.ASSETS_DIRECTORY, presentation.getId()
							+ presentation.getMp3().replace(ApplicationConstants.SLASH, ""));
					Log.i(TAG, "Mp3 exists ons filesystem? " + file.exists());

					ParleysMediaPlayer.setDataSource(file.getAbsolutePath());
				}
			}
			ParleysMediaPlayer.moveToPoint(msecs);
		}
	}

	final Runnable updateTimer = new Runnable() {

		@Override
		public void run() {
			final Handler handler = new Handler();
			if (guiIsUpdating) {
				setTitle(getString(R.string.chapters_time, TimeUtil
						.getElapsedTimeMinutesSecondsString(ParleysMediaPlayer.getCurrentPosition())));
				handler.postDelayed(this, 1000);
			}
		}

	};

	@Override
	public boolean onCreateOptionsMenu(final Menu menu) {

		MenuItem generalInfoMenuItem = menu.add(0, 0, 0, getString(R.string.general_info));
		generalInfoMenuItem.setIcon(android.R.drawable.ic_menu_info_details);

		if (online) {
			MenuItem previewSlidesMenuItem = menu.add(1, 1, 0, getString(R.string.preview_slides));
			previewSlidesMenuItem.setIcon(android.R.drawable.ic_menu_gallery);
			MenuItem downloadMenuItem = menu.add(2, 2, 0, getString(R.string.download));
			downloadMenuItem.setIcon(android.R.drawable.ic_menu_save);

			dbAdapter.openForReading();
			if (dbAdapter.isPresentationPresentInDb(presentation.getId())) {
				menu.setGroupEnabled(2, false);
			}
			dbAdapter.close();

		} else {
			MenuItem slidesMenuItem = menu.add(1, 1, 0, getString(R.string.slides));
			slidesMenuItem.setIcon(android.R.drawable.ic_menu_gallery);
		}
		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		MenuItem menuItem = menu.findItem(3);
		if (menuItem == null) {
			menuItem = menu.add(1, 3, 0, getString(R.string.pause));
		}
		ParleysMediaPlayer.initializePlayButton(menuItem, this.getApplicationContext());

		return true;
	}

	/* Handles item selections */
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			Log.d(TAG, "First menu button pressed");
			gotoDetailActivity(space, channel, presentation, online);
			return true;
		case 1:
			Log.d(TAG, "Second menu button pressed");
			gotoSlidesActivity(space, channel, presentation, online);
			return true;
		case 2:
			Log.d(TAG, "Third menu button pressed");
			DownloadTask task = new DownloadTask(presentation, channel, space);
			getInjector().injectMembers(task);
			task.start();
			return true;
		case 3:
			Log.d(TAG, "Pause/Play menu button pressed");
			ParleysMediaPlayer.toggle(channel, presentation, online);
			return true;
		}
		return false;
	}

}
